﻿using System;
using System.Web.Http;
using FellowshipOne.API;
using FellowshipOne.API.Base;
using FellowshipOne.API.People.Model;
using MasVida.WebApi.Controllers.Interfaces;
using MasVida.WebApi.Models.DataObject;
using MasVida.WebApi.Models.Requests;
using Newtonsoft.Json.Linq;

namespace MasVida.WebApi.Controllers
{
    public class PushNotificationsController : ApiBaseController
    {
        public PushNotificationsController()
        {
        }

        public PushNotificationsController(IRestClient restClient)
        {
            RestClient = restClient;
        }

        [HttpPost]
        public void RegisterToken(JObject jsonObjet)
        {
            WebHookPushRequest webHookPushRequest = GetRequestFromJObject(jsonObjet);
            IRestClient restClient = GetRestClient(webHookPushRequest.AccessTicket);

            Person person = restClient.PeopleRealm.People.Get(webHookPushRequest.PersonId);
            person.MemberEnvelopeCode = webHookPushRequest.Token;

            restClient.PeopleRealm.People.Update(person, person.ID.ToString());
        }

        private WebHookPushRequest GetRequestFromJObject(JObject jobject)
        {
            return new WebHookPushRequest()
            {
                ApiKey = jobject["ApiKey"]?.Value<string>(),
                AccessTicket = jobject["AccessTicket"]?.ToObject<F1OAuthTicket>(),
                PersonId = jobject["PersonId"]?.Value<string>(),
                Token = jobject["Token"]?.Value<string>()
            };
        }
    }
}